/******************************************************************************
This file is part of AppKit.
Project: appkit
Author : FergusZeng
Email  : cblock@126.com
git	   : https://gitee.com/newgolo/appkit.git
*******************************************************************************
MIT License

Copyright (c) 2022 cblock@126.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#pragma once

#include <signal.h>

#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "appkit/async.h"
#include "appkit/atomic.h"
#include "appkit/basetype.h"
#include "appkit/thread.h"

namespace appkit {
class Application;
class Component {
    DECL_CLASSMETA(Component)

public:
    using Ptr = std::shared_ptr<Component>;
    DECL_PROPERTY(std::string, "Component", name, setName)
public:
    Component() {}
    virtual ~Component() {}
    virtual bool onInit() { return true; }
    virtual bool onStart() { return true; }
    virtual bool onStop() { return true; }
    virtual bool onDeinit() { return true; }
    virtual bool addTask(const AsyncTaskQueue::Task& task);
    virtual bool isRunning();

private:
    friend Application;
    Application* m_context{nullptr};
    std::atomic<bool> m_runFlag{false};
};

/**
 * @brief 应用框架
 * @class Application
 * @note 该应用框架可用于对线程数量有严格要求的场景
 */
class Application : public Component, public Runnable {
    DECL_CLASSMETA(Application)

public:
    Application();
    virtual ~Application();
    /**
     * @brief 增加组件
     * @param name 组件名称
     * @param comp 组件指针
     */
    bool addComponent(const std::string& name, Component::Ptr comp);

    /**
     * @brief 移除组件
     * @param name 组件名称
     */
    bool removeComponent(const std::string& name);

    /**
     * @brief 获取组件
     * @tparam CMPT 组件类型
     * @param name 组件名称
     * @return 组件指针
     */
    template <typename CMPT>
    std::shared_ptr<CMPT> getComponent(const std::string& name) {
        int idx = findComponent(name);
        if (idx < 0) {
            return nullptr;
        }
        return std::dynamic_pointer_cast<CMPT>(m_components[idx].second);
    }

    /**
     * @brief 执行任务
     * @param task
     * @return true
     * @return false
     */
    bool addTask(const AsyncTaskQueue::Task& task) final;

    /**
     * @brief 注册信号处理函数
     * @param signo
     * @param handler
     * @return true
     * @return false
     */
    bool registerSignal(int signo, std::function<void()> handler);
    /**
     * @brief 启动应用
     * @param workers 最大线程数
     * @return true
     * @return false
     */
    bool startup(int workers = 1);

    /**
     * @brief 退出应用
     */
    void quit();

private:
    void run(const Thread& thread) final;
    int findComponent(const std::string& name);

private:
    Thread m_thread{"Application"};
    AtomicVector<std::pair<std::string, Component::Ptr>> m_components;
    std::mutex m_componentsMutex;
    std::shared_ptr<AsyncTaskQueue> m_taskQueue{nullptr};
};

}  // namespace appkit
